package com.zxy.demo.controller;

import java.util.ArrayList;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags={"jsr303使用的2种方式测试"})
@RestController
public class TestJsr303Controller {
	
	/**
	 * 校验失败时，直接报http状态码400 ，抛出 org.springframework.web.bind.MethodArgumentNotValidException
	 * @param vo
	 * @return
	 */
	@ApiOperation(value = "使用Valid,校验失败抛出异常", httpMethod = "POST")
	@PostMapping("jsrValid")
	public String testJsr303ThrowException(@Valid @RequestBody JsrTestVo vo) {
		System.out.println(vo);
		return "success";
	}
	
	/**
	 * 由于方法参数里面有BindingResult，因此校验失败不会抛异常，它把错误信息都放在了BindingResult
	 * @param vo
	 * @param bindingResult
	 * @return
	 */
	@ApiOperation(value = "使用Valid+BindingResult,校验失败不会抛异常", httpMethod = "POST")
	@PostMapping("jsrValidByBindingResult")
	public String testJsr303ByBindingResult(@Valid @RequestBody JsrTestVo vo, BindingResult bindingResult) {
		System.out.println(vo);
		if(bindingResult.hasErrors()) {
			ArrayList<String> errors = new ArrayList<String>();
	        for (ObjectError objectError : bindingResult.getAllErrors()) {
	            errors.add(objectError.getDefaultMessage());
	        }
			return "error:" + String.join(",", errors);
		}
		return "success";
	}

}

class JsrTestVo {
	@NotBlank(message="姓名不能为空")
	private String name;
	@NotNull(message = "年龄不能为null")
	@Max(value = 150, message="年龄最大不能超过150")
	private Integer age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "JsrTestVo [name=" + name + ", age=" + age + "]";
	}
	
}